<?php
namespace Home\Model;
use Think\Model;
/**
 * CREATE TABLE art_enroll(
 *	-> id INT(8) NOT NULL PRIMARY KEY AUTO_INCREMENT,
 *  -> uid INT(8) NOT NULL,
 *  -> enrolltime INT(20) NOT NULL,
 *  -> uptime INT(20) NOT NULL,
 *  -> ispayed INT(8) NOT NULL,
 *  -> major VARCHAR(45) NOT NULL,
 *  -> examcenter INT(8) NOT NULL,
 *  -> FOREIGN KEY(uid) REFERENCES art_user(id) ON UPDATE CASCADE ON DELETE RESTRICT);
*/
class EnrollModel extends Model{
	private $id;	// 报名ID
	private $_uid;	// 用户id
	private $_enrolltime;	// 创建时间
	private $_uptime;	// 最后更新时间
	private $_ispayed;	// 是否已经支付过
	private $_major;	// 考试专业	=>	根据这个计算价格
	private $_examcenter;	// 考试考点
	const IS_PAYED = 1;	// 是否支付过，0表示还没有支付
	const ISNOT_PAYED = 0;

	public function addOne($uid, $majors, $examcenter){
		$this->_uid = $uid;
		$this->_enrolltime = time();
		$this->_uptime = time();
		$this->_ispayed = self::ISNOT_PAYED;
		$this->_major = implode(',', $majors);
		$this->_examcenter = $examcenter;
		if($this->isHas())return false;
		return $this->add($this->convertData());
	}

	public function setPayed($id){
		$data['id'] = $id;
		$data['uptime'] = time();
		$data['ispayed'] = self::IS_PAYED;
		return $this->save($data);
	}

	public function checkPayed($id){
		$data = $this->where(array('id'=>$id))->find();
		if(empty($data)){
			return false;
		}else{
			return $data['ispayed'];
		}
	}

	public function deleteOne($id){
		$data = $this->where(array('id'=>$id))->find();
		if($data['ispayed'] == self::IS_PAYED){
			return false;	// 已经支付，不许取消
		}
		return $this->where(array('id'=>$id))->delete();
	}

	public function getInfoByUid($uid){
		return $this->where(array('uid'=>$uid))->select();
	}

	private function convertData($needuid = 1, $needid = 0){
		$res =  array(
			'enrolltime'	=>	$this->_enrolltime,
			'uptime'	=>	$this->_uptime,
			'ispayed'	=>	$this->_ispayed,
			'major'	=>	$this->_major,
			'examcenter'	=>	$this->_examcenter
		);
		if($needuid != 0){
			$res['uid']	=	$this->_uid;
		}
		if($needid != 0){
			$res['id']	= $this->_id;
		}
		return $res;
	}

	private function isHas(){
		$info = $this->getInfoByUid($this->_uid);
		if(empty($info))return false;
		foreach ($info as $key => $value) {
			$arr1 = explode(',', $value['major']);
			$arr2 = explode(',', $this->_major);
			$tmp = array_diff($arr1, $arr2);
			if(empty($tmp) && $value['examcenter'] == $this->_examcenter){
				return true;
			}
		}
		return false;
	}

}
